<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// 
//  user_model.php
//  www.6block.com
//  
//  Created by Will_Lee on 2011-05-21.
//  Copyright 2011 lishuzu. All rights reserved.
// 


class Tag_model extends CI_Model
{
	function __construct(){
		parent::__construct();
		$this->load->model('user_model');
		$this->load->library('datacache');
		$this->user = $this->session->userdata('user') ? $this->session->userdata('user') : '';
		$this->uid = $this->uri->segment(3) ? intval($this->uri->segment(3)) : $this->user['uid'];
	}
	
	//处理作品tag
	function tag_batch($workid, $tags) {
		
		$tagarr = array();
		$tagnames = empty($tags)?array():array_unique(explode(' ', $tags));
		if(empty($tagnames)) return $tagarr;

		$vtags = array();
		$query = $this->db->query("SELECT tagid, tagname, close FROM ".$this->db->dbprefix('tag')." WHERE tagname IN (".simplode($tagnames).")");
		foreach ($query->result_array() as $value) {
			$value['tagname'] = addslashes($value['tagname']);
			$vkey = md5($value['tagname']);
			$vtags[$vkey] = $value;					
		}
		$updatetagids = array();
		foreach ($tagnames as $tagname) {
			if(!preg_match('/^([\x7f-\xff_-]|\w){3,20}$/', $tagname)) continue;

			$vkey = md5($tagname);
			if(empty($vtags[$vkey])) {
				$setarr = array(
					'tagname' => $tagname,
					'uid' => $this->user['uid'],
					'dateline' => now(),
					'worknum' => 1
				);
				$this->db->insert('tag', $setarr, 1);
				$tagid = $this->db->insert_id();
				$tagarr[$tagid] = $tagname;
			} else {

				if(empty($vtags[$vkey]['close'])) {
					$tagid = $vtags[$vkey]['tagid'];
					$updatetagids[] = $tagid;
					$tagarr[$tagid] = $tagname;
				}
			}
		}
		
		if($updatetagids){
			$this->db->query("UPDATE ".$this->db->dbprefix('tag')." SET worknum=worknum+1 WHERE tagid IN (".simplode($updatetagids).")");	
		} 
		$tagids = array_keys($tagarr);
		$inserts = array();
		foreach ($tagids as $tagid) {
			$inserts[] = "('$tagid','$workid', '".$tagarr[$tagid]."')";
		}
		if($inserts) $this->db->query("REPLACE INTO ".$this->db->dbprefix('tagwork')." (tagid,workid,tagname) VALUES ".implode(',', $inserts));
		return $tagarr;
	}
	
	//更新作品tag tag:string oldtag array
	function update_tag($tag, $oldtag, $wid){
		$oldtagstr = empty($oldtag)?'':implode(' ', unserialize($oldtag));
		$tagarr = array();
		if($tag != $oldtagstr) {
			if(!empty($oldtag)) {
				//先把以前的给清理掉
				$oldtags = array();
				$query = $this->db->query("SELECT tagid, workid FROM ".$this->db->dbprefix('tagwork')." WHERE workid='$wid'");
				foreach ($query->result_array() as $value) {
					$oldtags[] = $value['tagid'];
				}
				
				if($oldtags) {
					$this->db->query("UPDATE ".$this->db->dbprefix('tag')." SET worknum=worknum-1 WHERE tagid IN (".simplode($oldtags).")");
					$this->db->query("DELETE FROM ".$this->db->dbprefix('tagwork')." WHERE workid='$wid'");
				}
			}
			$tagarr = $this->tag_batch($wid, $tag);
			
			//更新附表中的tag
			return empty($tagarr)?'':$tagarr;
		}else{
			return $oldtag;
		}
	}
	
	// 需要更新 needupdate 1需要更新	
	function get_cache($needupdate = '0'){
		//加载TAG缓存文件
		$cachefilename = APPPATH."cache/data_tag.php";
		$cachetime = 3600;
		if ($needupdate) {
			if(file_exists($cachefilename) && (filemtime($cachefilename) + $cachetime) > time()) {
				$tags = $this->config->item('tag');
			 } else {
				$this->datacache->tag_cache();
				$tags = $this->config->item('tag');
			}
			return $tags;
		}else{
			$tags = $this->config->item('tag');
			return $tags;
		}
	}
}